'use strict';

const {
  secret
} = require('../util/tools.js');
const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const atob = require('atob');
const btoa = require('btoa');

class SignController extends Controller {

  async getList() {
    const ctx = this.ctx;
    const userList = await ctx.service.sign.getList();
    ctx.body = {
      userList
    }
  }

  /**
   * 登录接口,返回token
   * @return {Object}
   **/
  async login() {
    const ctx = this.ctx;
    const userInfo = ctx.request.body.userInfo;
    if (typeof userInfo !== 'string') {
      ctx.body = {
        code: 403,
        msg: '非法请求',
      };
      return;
    }
    const info = this.encode(userInfo).data;
    const res = await this.service.sign.selectInfo(info);
    const isOk = bcrypt.compareSync(info.userPwd, res[0]['userPwd'])
    if (isOk) {
      ctx.body = {
        code: 200,
        token: this.newToken(res[0]["id"]),
        message: "登录成功!"
      }
    } else {
      ctx.body = {
        code: 20001,
        message: "信息有误,检查用户名密码"
      }
    }
  }

  /**
   * 注册接口,返回信息
   * @return {Object}
   **/
  async register() {
    const ctx = this.ctx;
    const userInfo = ctx.request.body.userInfo;
    if (typeof userInfo !== 'string') {
      ctx.body = {
        code: 403,
        msg: '非法请求',
      };
      return;
    }
    const info = this.encode(userInfo).data;
    const salt = bcrypt.genSaltSync(10)
    // 对明文加密
    const pwd = bcrypt.hashSync(info.userPwd, salt)
    const hasuser = await ctx.service.sign.hasUser();
    info.userPwd = pwd;
    info.salt = salt;
    if (!hasuser) {
      const res = await ctx.service.sign.insertUser(info)
      const {
        insertId
      } = res
      if (insertId) {
        ctx.body = {
          code: 200,
          message: "注册成功!"
        }
      } else {
        // 写入日志
        ctx.body = {
          code: 200,
          message: "未知原因,注册失败!"
        }
      }
    } else {
      ctx.body = {
        code: 2001,
        message: "当前用户已存在!"
      }
    }
    // 验证比对,返回布尔值表示验证结果 true表示一致，false表示不一致
    // const isOk = bcrypt.compareSync('123456', pwd1)

  }

  /**
   * 生成返回给前台的token
   * @return {String}
   **/
  newToken(insertId) {
    const STK = `${Date.now()}@${insertId}@${this.random()}`
    return btoa(STK)
  }

  /**
   * 解析token中的id
   * @return {String}
   **/
  decodeID(base64) {
    const decode = atob(base64);
    return decode.split("@")[1];
  }

  /**
   * 生成随机字符串
   * @return {String}
   **/
  random(length = 8) {
    let str = Math.random().toString(36).substr(2);
    if (str.length >= length) {
      return str.substr(0, length);
    }
    str += random(length - str.length);
    return str;
  }
  /**
   * 解析登录注册传来的参数
   * @return {String}
   **/
  encode(token) {
    return jwt.verify(token, secret, (error, decoded) => {
      if (error) {
        console.error(error.message);
        return;
      }
      return decoded;
    });
  }
}

module.exports = SignController;